package com.tian.app.controller;

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.mybatis.web.domain.Condition;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import com.tian.app.domain.AppUser;
import com.tian.app.domain.vo.WechatLoginVo;
import com.tian.app.service.IAppUserService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import io.swagger.annotations.ApiOperation;

/**
 * 小程序登录
 * 
 * @author jerry
 */
@RestController
@RequestMapping("/oauth")
public class LoginController extends BaseController {
	
	@Autowired
	private WxMaService wxService;
	
	@Autowired
	private TokenService tokenService;
	
	@Autowired
	private IAppUserService appUserService;

	/**
     * 微信小程序登陆
     */
	@PostMapping(value = "/third/wechat-ma")
	@ApiOperation(value = "微信小程序登录",notes = "微信小程序登录")
    public AjaxResult wechatMp(@RequestBody WechatLoginVo wechatLoginVo) {
		try {
			WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(wechatLoginVo.getCode());
			String sessionKey = session.getSessionKey();
			String openid = session.getOpenid();
			// 解密用户信息
			WxMaUserInfo wxUser = wxService.getUserService().getUserInfo(sessionKey, wechatLoginVo.getEncryptedData(), wechatLoginVo.getIv());
			
			AppUser entity = new AppUser();
			entity.setOpenid(openid);
			
			AppUser appUser = appUserService.getOne(Condition.getQueryWrapper(entity));
			if(appUser == null){
				// 注册
				appUser = new AppUser();
				appUser.setAvatar(wxUser.getAvatarUrl());
				appUser.setNickName(wxUser.getNickName());
				appUser.setGender(wxUser.getGender());
				appUser.setOpenid(wxUser.getOpenId());
				appUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
				appUser.setLoginDate(new Date());
				appUserService.save(appUser);
			}else{
				// 登录
				appUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
				appUser.setLoginDate(new Date());
				appUserService.updateById(appUser);
			}
			
			LoginUser user = new LoginUser();
			user.setUserid(appUser.getId());
			user.setUsername(wxUser.getNickName());
			return AjaxResult.success(tokenService.createToken(user));
		} catch (Exception e) {
			e.printStackTrace();
		}
        return AjaxResult.error("微信小程序参数配置错误");
    }
    
}
